import { RouteRecordRaw } from "vue-router";
import router from "@/router";

import { defineStore } from "pinia";
import { constantRoutes, Layout } from "@/router";
import MenuApi, { Button, HomeMenuTree } from "@/api/sys/menu";

export const usePermissionStore = defineStore("permission", () => {
  /** 所有路由，包括静态和动态路由, Tags使用 */
  const routes = ref<RouteRecordRaw[]>([]);

  /** 路由是否已加载 */
  const isRoutesLoaded = ref(false);

  /**
   * 菜单数据
   */
  const menuList = ref<HomeMenuTree[]>([]);

  /**
   * 扁平结构菜单数据
   */
  const flatMenuList = ref<HomeMenuTree[]>([]);

  /**
   * 按钮数据
   */
  const buttonList = ref<Button[]>([]);

  /**
   * 生成动态路由
   */
  function generateRoutes() {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      MenuApi.queryHomeMenu()
        .then((data) => {
          if (data.dataList) {
            // 过滤掉隐藏的菜单
            Object.assign(menuList.value, {
              ...data.dataList.filter((x) => x.hidden === false),
            });
            // 平级菜单用作通过按钮跳转的菜单权限
            Object.assign(flatMenuList.value, {
              ...flattenTree(data.dataList),
            });
            // 包括隐藏的菜单，有些页面会通过按钮跳转
            const dynamicRoutes = transformRoutes(data.dataList);
            routes.value = constantRoutes.concat(dynamicRoutes);
            isRoutesLoaded.value = true;
            resolve(dynamicRoutes);
          } else {
            ElMessage({
              type: "info",
              message: `该用户没有任何权限！`,
            });
            return reject("该用户没有任何权限！");
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 重置路由
   */
  function resetRouter() {
    //  从 router 实例中移除动态路由
    routes.value.forEach((route) => {
      if (route.name && !constantRoutes.find((r) => r.name === route.name)) {
        router.removeRoute(route.name);
      }
    });
    routes.value = [];
    menuList.value = [];
    buttonList.value = [];
    isRoutesLoaded.value = false;
    router.replace({ path: "/login" });
  }

  /**
   * 查询指定菜单下的按钮
   * @param menuId 菜单ID
   */
  const loadButton = async (menuId: string) => {
    if (!menuId) {
      return;
    }
    const { dataList } = await MenuApi.queryButton(menuId);
    Object.assign(buttonList.value, { ...dataList });
    return buttonList.value;
  };

  return {
    routes,
    menuList,
    flatMenuList,
    buttonList,
    isRoutesLoaded,
    generateRoutes,
    loadButton,
    resetRouter,
  };
});

const modules = import.meta.glob("@/views/**/**.vue");
const transformRoutes = (routelist: HomeMenuTree[]) => {
  //读取当前项目中Views文件夹下的vue后缀的文件
  const asyncRoutes: RouteRecordRaw[] = [];
  routelist.forEach((route) => {
    const tmpRoute: RouteRecordRaw = {
      name: route.routerName,
      meta: {
        title: route.name,
        id: route.id,
        parentId: route.parentId,
        menuType: route.menuType,
        icon: route.icon,
        affix: route.routerName === "home" ? true : false,
        keepAlive: true,
      },
      path: route.routerUrl,
      redirect: route.redirect,
      children: [],
    };

    if (route.webFilePath === "Layout") {
      tmpRoute["component"] = Layout;
    } else {
      const component = modules[`/src/views/${route.webFilePath}.vue`];
      if (component) {
        tmpRoute["component"] = component;
      } else {
        tmpRoute["component"] = modules[`/src/views/error-page/404.vue`];
      }
    }

    if (route.children) {
      tmpRoute.children = transformRoutes(route.children);
    }
    asyncRoutes.push(tmpRoute);
  });
  return asyncRoutes;
};

function flattenTree(tree, result = []) {
  tree.forEach((node) => {
    // 将当前节点的信息添加到结果数组中
    result.push(node);

    // 如果当前节点有子节点，则递归调用 flattenTree 函数
    if (node.children && node.children.length > 0) {
      flattenTree(node.children, result);
    }
  });

  return result;
}
